package deprecated.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import util.DomainUtils;
import util.FormArgumentsException;

/**
 * Servlet implementation class DisconnectServlet
 */
public class DisconnectServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DisconnectServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(false);

		try {
			checks(request);
			session.setAttribute(DomainUtils.CURRENT_USER_STRING, null);
		}
		catch(Exception e) {
			if((e instanceof FormArgumentsException) == false) {
				request.setAttribute(DomainUtils.ALERT_ERROR_STRING, "An error occur on the server.");
			}
			
			DomainUtils.keepParametersContent(request);
		}
		
		request.getRequestDispatcher("pages/index.jsp").forward(request, response);
	}

	private void checks(HttpServletRequest request) throws Exception {

		HttpSession session = request.getSession(false);
		
		
		//Checking session
		if(session == null || session.getAttribute(DomainUtils.CURRENT_USER_STRING) == null) {
			request.setAttribute(DomainUtils.ALERT_ERROR_STRING, 
					"You are not currently connected. May be the session expired.");
			throw new FormArgumentsException();
		}
	}
}
